#coding=utf-8
import re,logging,os,urllib,time
from google.appengine.api import mail
from google.appengine.ext import db,webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.api.labs import taskqueue

from ad import get_latest_ad, send_ad
from counter import Counter, COUNTER_NAME

APPLICATION = os.environ['APPLICATION_ID']
SERVER = '%s.appspotmail.com'%APPLICATION

SENDERS = ['taobao',
'Jay',
'Young',
'no-reply',
'hello',
'taobao8',
'taobao2',
'google_fan',
'Friend',
'Kate',
'Lucy',
'Rose',
'Jack',
'Candy',
'Ada',
'Amy',
'Cathy',
'Elma',
'Gill',
'Jessie',
'Jessica',
'Eric',
'Geroge',
]

EMAIL_PORTAL_URL = 'http://email-portal.appspot.com/get'
RE_EMAIL = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",re.IGNORECASE)

INVALIDDOMAINS = ['etang.com',
'sian.com', 
'avl.com.cn',
'0451.com',
'fm365.com',
'ynmail.com',
'cmmail.com',
'suhoo.com',
'wz163.com',
'com.cn',
'shou.com',
'sohu.com.cn',
'hotmai.com',
'fc18.com',
'168.com',]

class RejectedEmail(db.Model):
  addr = db.StringProperty(required=True)
  
  #subject = db.StringProperty(multiline=True)
  #content = db.TextProperty()
  
  flag = db.BooleanProperty(default=False)   

class Sender(db.Model):
  name = db.StringProperty(required=True)
  
def get_sender():
  while True:
    query = Sender.all()
    if query.count() != 0:
      s = query.fetch(1)[0]
      return '%s@%s'%(s.name, SERVER)
    Sender(name=SENDERS[0]).put()
    
def change_sender():
  query = Sender.all()
  if query.count() == 0:
    return
  
  current = query.fetch(1)[0].name
  for s in query:s.delete()
  
  i = SENDERS.index(current)
  i = i + 1
  if i == len(SENDERS):
    i = 0
    
  Sender(name=SENDERS[i]).put()
  
class Email(db.Model):
  addr = db.StringProperty(required=True)

def valid_email_filter(addr):
  try:
    user, domain = addr.split('@')
    user = user.strip()
    domain = domain.strip()
  except ValueError:
    return None
  else:
    if domain in INVALIDDOMAINS:
      logging.info("Invalid Domain:%s"%addr)
      return None
    return '%s@%s'%(user, domain)

def get_mail():
  while True:
    n = Email.all().count()
    if n != 0:
      email = Email.all().fetch(1)[0]
      r = email.addr
      email.delete()
      return r
    
    try:
      addrs = urllib.urlopen( EMAIL_PORTAL_URL ).read().split('<br/>')[:-1]
    except IOError, e:
      logging.error('Error in Geting mail:%s'%e)
    
    else:
      emails = []
      for a in addrs:
        a2 = valid_email_filter(a)
        if a2:
          emails.append(Email(addr=a2))
  
      db.put(emails)
      
class MailSender(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    
    ad = get_latest_ad()
    send_ad(ad, sender=get_sender(), receiver=addr)
    logging.debug( '%s Sended'%addr )
    self.response.out.write(addr)

class MailSender2(webapp.RequestHandler):
  def get(self):
    '''
    sended_counter = Counter(COUNTER_NAME)
    n = sended_counter.get_count()
    

    if n >= 500:
      sended_counter.reset()
      logging.info('500 mails are sended!')
      return
    '''  
    email = get_mail()
    if not email:return
    
    ad = get_latest_ad()
    send_ad(ad, sender=get_sender(), receiver=email)
    #sended_counter.change_count(1)
    #taskqueue.add(url='/send_mail2', method='GET')
    
    self.response.out.write(email)

class MailSender3(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    mail.send_mail(sender=get_sender(),
      to=addr,
      subject='hello',
      body='hello', 
      html='hello')
    self.response.out.write(addr)

class MailHandler(InboundMailHandler):
  def receive(self, message):
    _subject = message.subject
    _sender = message.sender
    bodies = message.bodies(content_type='text/plain')
    allBodies = "";
    for body in bodies:
        allBodies = allBodies + "\n---------------------------\n" + body[1].decode()  
    
    if allBodies.find('answer=69585') != -1:
      change_sender()
      logging.critical('Sender Changed!')      
      
    info = '发送者:%s\n标题:%s\n正文:%s\n'%(_sender, _subject, allBodies)
    logging.info(info)
        
    addrs = []
    emails = RE_EMAIL.findall(allBodies)
    #logging.info('*'.join(emails))
    for e in emails:
      if not e:continue
      e2 = e.strip()
      if e2.split('@')[-1] in [SERVER, 'google.com']:
          continue
      addrs.append(e2)
    addrs = list(set(addrs))
    #logging.info('~'.join(addrs))
    for addr in addrs:
      RejectedEmail(addr=addr).put()

def post_rejected(email, subject='s', content='c'):
  import urllib
  import urllib2

  url = 'http://remail.cndjango.com/reject'
  values = {'email': email,
            'sub': subject,
            'content': content
            }
  
  data = urllib.urlencode(values)
  req = urllib2.Request(url, data)
  response = urllib2.urlopen(req)
  the_page = response.read()
  return the_page

class PostRejected(webapp.RequestHandler):
  def get(self):
    n = RejectedEmail.all().count()
    if n == 0:return
    
    r = RejectedEmail.all().fetch(1)[0]
    post_rejected(r.addr)
    r.delete()
    self.response.out.write(r.addr)
    
      
      
